

use clap::{Parser, Subcommand};
use gfsc::*;

type Result<T> = anyhow::Result<T>;



#[derive(Parser, Debug)]
#[clap(
    name = "gfs router helper",
    version,
    author,
    about = "how to write a router.json for gfsc"
)]
struct Cli {
    #[clap(subcommand)]
    command: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    ///  create a example router.json for gfsc
    Create {          
        #[clap(name = "fname", long, default_value = "router.json")]
        fname: String,
    },    
    /// check if the router.json is ok.
    Check {        
        #[clap(name = "fname", long, default_value = "router.json")]
        fname: String,
    },
    ///  a simple config.
    Suggest{},
}


#[tokio::main]
pub async fn main() {

    let cli = Cli::parse();

    match cli.command {
      Command::Create {fname } => {
        if let Err(err) = create_config(&fname).await{
            println!("{:#?}", err);
        }       
      },    
      Command::Check {fname } => {
        if let Err(err) = check_config(&fname).await{
            println!("{:#?}", err);
        }
      },
      Command::Suggest {} => {
        let sub = r#"
        "nodes": [
            {"max":127,"min":0, "writer":"http://localhost:9996","readers":["http://localhost:9996","http://localhost:9997"]},
            {"max":255,"min":128, "writer":"http://localhost:9998","readers":["http://localhost:9998","http://localhost:9999"]} 
            ]
        "#;
        println!("{}", sub); 
      }  
  }

}
 

async fn create_config(fname:&str)->Result<()> {
    let router = GfsRouter::try_generate(fname);    
    router.check()?;
    Ok(())   
}

async fn check_config(fname:&str)->Result<()> {
    let router = gfsc_new_router(fname)?;
    router.check()?;
    println!("config is ok!");
    Ok(())   
}